import gmail
import re
import os

class Sourcepress(object):

	def __init__(self):
		pass

	def parseCode(self, content):
		ret = ""
		firstLineOfComment = True
		commentFound = False
		readSomething = False
		startsWithComment = False
		comment = ""
		for l in content.split("\n"):
			if "//" in l:
				commentFound = True
				if firstLineOfComment:
					if readSomething:
						ret += "[/sourcecode]\n"
					firstLineOfComment = False
				ret += re.sub("//", "", l)
			else:
				if commentFound:
					ret += "[sourcecode language=cpp]\n"
					commentFound = False
					firstLineOfComment = True
				ret += l+"\n"
				readSomething = True

		return ret+"[/sourcecode]"

	def generate(self, post):

		lines = post.split("\n")

		i = 0

		fullPost = ""

		for l in lines:
			m = re.match("file:(.*)", l)
			if m:
				sourceFile = m.group(1)
				if os.path.exists(sourceFile):
					f = open(sourceFile)
					content = re.sub("\t", "    ", f.read())
					content = self.parseCode(content)
					lines[i] = content
					f.close()
			i += 1

		fullPost = ""

		for l in lines:
			fullPost += l + "\n"

		return fullPost

	def post(self, token, post):

		fullPost = self.generate(post)

		gmail.sendEmail("whoever@gmail.com", token+"@post.wordpress.com", "test post", fullPost)
